package com.sfang.common.util.encrypt;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class DESUtil {

    private static byte[] keys = { (byte) 0x12, (byte) 0x34, (byte) 0x56,
            (byte) 0x78, (byte) 0x90, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF };
    private static Logger LOGGER = LoggerFactory.getLogger(DESUtil.class);

    public static String decrypt(String message, String key)  {
        try {

            byte[] bytesrc = fromHexString(message);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
            IvParameterSpec iv = new IvParameterSpec(keys);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
            byte[] retByte = cipher.doFinal(bytesrc);
            return new String(retByte, "utf-8");
        }catch (Exception e){
            LOGGER.error(String.format("des decrypt error,data-【%s】 error-【%s】",message,
                    JSON.toJSONString(e)));
            return message;
        }
    }

    private static byte[] fromHexString(String hexStr) {
        byte[] bytesrc = new byte[hexStr.length() / 2];
        for (int i = 0; i < bytesrc.length; i++) {
            String byteString = hexStr.substring(2 * i, 2 * i + 2);
            int byteValue = Integer.parseInt(byteString, 16);
            bytesrc[i] = (byte) byteValue;
        }
        return bytesrc;
    }
}
